<template>
    <div ref="chartRef" class="chart-container"></div>
  </template>
  
  <script>
  import { ref, onMounted } from 'vue';
  import * as echarts from 'echarts';
  import { getMedicalRecordListByUserId } from '@/api/medicalRecord';
  
  export default {
    name: 'HealthDataChart',
    setup() {
      const chartRef = ref(null);
      const chartInstance = ref(null);
  
      // 获取医疗记录数据
      const fetchMedicalRecords = async () => {
        try {
          const userId = parseInt(localStorage.getItem('id'));
          const params = {
            startDate: "2000-01-01",
            endDate: "3000-01-01",
            pageIndex: 1,
            pageSize: 5
          };
          const response = await getMedicalRecordListByUserId(userId, params);
          return response.data.records;
        } catch (error) {
          console.error('获取医疗记录失败:', error);
          throw error;
        }
      };
  
      // 初始化图表
      const initChart = async () => {
        try {
          const records = await fetchMedicalRecords();
          if (!records || records.length === 0) {
            console.log('没有数据可显示');
            return;
          }
  
          // 提取数据
          const recordDates = records.map(record => record.recordDate.split('T')[0]);
          const stepsData = records.map(record => record.steps);
          const sleepDurationData = records.map(record => record.sleepDuration);
          const waterIntakeData = records.map(record => record.waterIntake);
  
          // 配置图表选项
          const option = {
            title: {
              text: '健康数据统计'
            },
            tooltip: {
              trigger: 'axis'
            },
            legend: {
              data: ['步数', '睡眠时长(小时)', '饮水量(ml)']
            },
            xAxis: {
              type: 'category',
              data: recordDates
            },
            yAxis: [
              {
                type: 'value',
                name: '步数'
              },
              {
                type: 'value',
                name: '睡眠时长(小时)',
                inverse: true // 睡眠时长刻度反转
              },
              {
                type: 'value',
                name: '饮水量(ml)'
              }
            ],
            series: [
              {
                name: '步数',
                type: 'line',
                yAxisIndex: 0,
                data: stepsData
              },
              {
                name: '睡眠时长(小时)',
                type: 'line',
                yAxisIndex: 1,
                data: sleepDurationData
              },
              {
                name: '饮水量(ml)',
                type: 'line',
                yAxisIndex: 2,
                data: waterIntakeData
              }
            ]
          };
  
          // 初始化 ECharts 实例
          chartInstance.value = echarts.init(chartRef.value);
          chartInstance.value.setOption(option);
  
          // 窗口大小变化时重新调整图表大小
          window.addEventListener('resize', () => {
            chartInstance.value.resize();
          });
        } catch (error) {
          console.error('初始化图表失败:', error);
        }
      };
  
      // 页面挂载后初始化图表
      onMounted(() => {
        initChart();
      });
  
      return {
        chartRef
      };
    },
    unmounted() {
      // 组件销毁时释放 ECharts 实例
      if (chartInstance.value) {
        chartInstance.value.dispose();
      }
    }
  };
  </script>
  
  <style scoped>
  .chart-container {
    width: 100%;
    height: 500px;
  }
  </style>